﻿namespace MESTranslateToPLC.Service.BackgroudService;

public class MonitorConnectService : BackgroundService
{
    private ModbusService _modbusService;
    private ILogger<MonitorConnectService> _logger;

    public MonitorConnectService(ModbusService modbusService, ILogger<MonitorConnectService> logger)
    {
        _modbusService = modbusService;
        _logger = logger;
    }

    protected override async Task ExecuteAsync(CancellationToken stoppingToken)
    {
        while (!stoppingToken.IsCancellationRequested)
        {
            try
            {
                if (_modbusService.IsConnected)
                {
                    await _modbusService.ReadCoilsAsync(0, 1, 1);
                }
                else
                {
                    await _modbusService.Connect();
                    _logger.LogInformation("Modbus恢复连接");
                }
            }
            catch (Exception e)
            {
                _logger.LogWarning("Modbus连接异常:{0}",e.Message);
            }
            finally
            {
                await Task.Delay(100, stoppingToken);
            }
        }
        _modbusService.Disconnect();
    }
}